package net.homelinux.chaoswg.io.renga.core.gui.operations.reader;

import net.homelinux.chaoswg.io.higherorderfunctions.AbstractUnaryFunction;
import net.homelinux.chaoswg.io.higherorderfunctions.NAryFunction;
import net.homelinux.chaoswg.io.higherorderfunctions.UnaryFunction;
import net.homelinux.chaoswg.io.renga.core.animations.Animation;
import net.homelinux.chaoswg.io.renga.core.gui.operations.Operation;
import net.homelinux.chaoswg.io.renga.core.gui.operations.PrimitiveOperation;
import net.homelinux.chaoswg.io.renga.core.gui.operations.visualisations.Visualisation;
import net.homelinux.chaoswg.io.renga.core.registries.ReaderRegistry;

import org.jdom.Element;

public class PrimitiveOperationReader extends AbstractUnaryFunction<Operation, Element> implements UnaryFunction<Operation, Element>, OperationReader {

    public Operation apply(final Element arg0) throws IllegalArgumentException {
        try {
            final NAryFunction function = ((NAryFunction)Class.forName(arg0.getChild("function").getAttributeValue("type")).newInstance());
            
            Animation animation = null;
            
            if (arg0.getChild("animation") != null) {
                animation = ((Animation)Class.forName(arg0.getChild("animation").getAttributeValue("type")).newInstance());
            }
            
            final Element visualisationElement = arg0.getChild ("visualisation");
            final Visualisation vis = 
                    ((VisualisationReader) ReaderRegistry.getOperationRegistry().getOperationReader(Class.forName(visualisationElement.getAttributeValue("type")))).apply(visualisationElement);
            
            
            final CommonOperationReader cor = new CommonOperationReader ();
            final Operation toReturn = cor.apply(new PrimitiveOperation (function, animation, vis), arg0);
            
            return toReturn;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
